﻿using Mail.MiniProgram.Infrastructure;
using Mail.MiniProgram.Infrastructure.Utils.Async;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Mail.MiniProgram.Infrastructure.Utils.Extensions.BaseType;
using Mail.MiniProgram.Core.Results;
using Mail.MiniProgram.Core.Exceptions;
using Mail.MiniProgram.Core.Interfaces;

namespace Mail.MiniProgram.Core
{
    public class WxOpenClient:IOpenClient
    {
        public WxOpenClient()
        {

        }

        protected override string AppID { get => AppSettings.Configuration["Miniprogram:Wx:AppID"]; }
        protected override string AppSecret { get => AppSettings.Configuration["Miniprogram:Wx:AppSecret"]; }
        protected override string LoginUrl { get => "{0}/sns/jscode2session?appid={1}&secret={2}&js_code={3}&grant_type=authorization_code";  }
        protected override string AccessTokenUrl { get => "{0}/cgi-bin/token?grant_type=client_credential&appid={1}&secret={2}"; }



        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="code"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public async Task<LoginResult> GetLoginResult(string code)
        {
            using (var httpClient = new HttpClient())
            {
                try
                {
                    var LoginUrl = string.Format(this.LoginUrl, Config.ApiHost, AppID, AppSecret, code);
                    var response = await httpClient.GetAsync(LoginUrl);

                    var result = response.Content.ReadAsStringAsync().Result;

                    return JsonConvert.DeserializeObject<LoginResult>(result);
                }
                catch (Exception ex)
                {


                    return null;
                }
            }
        }
        /// <summary>
        /// token
        /// </summary>
        /// <param name="code"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public async Task<AccessTokenResult> GetAccesstoken(string code)
        {

            using (var wb = new HttpClient())
            {
                try
                {

                   var AccessTokenUrl = string.Format(this.AccessTokenUrl, Config.ApiHost, AppID, AppSecret);
                    var response = await wb.GetAsync(AccessTokenUrl);

                    var result = response.Content.ReadAsStringAsync().Result;

                    AccessTokenResult tokenResult = new AccessTokenResult();
                    return JsonConvert.DeserializeObject<AccessTokenResult>(result);
                }
                catch (Exception ex)
                {

                    return null;
                }
            }
        }


        public override async Task<AuthorizeResult> Authorize(string code)
        {
            AuthorizeResult authorizeResult = new AuthorizeResult();
            LoginResult loginResult = await this.GetLoginResult(code);

            if (loginResult.errcode != ReturnCode.请求成功)
            {
                throw new WxOpenException(loginResult.Explain);
            }

            AccessTokenResult accessTokenResult = await this.GetAccesstoken(code);
            if (accessTokenResult.errcode != ReturnCode.请求成功)
            {
                throw new WxOpenException(accessTokenResult.Explain);
            }
            authorizeResult.loginResult = loginResult;
            authorizeResult.accessTokenResult = accessTokenResult;
            return authorizeResult;

        }

     
    }
}
